package com.itmuch.cloud.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.itmuch.cloud.study.entity.Message;
import com.itmuch.cloud.study.entity.Order;
import com.itmuch.cloud.study.entity.Transport;
import com.itmuch.cloud.study.entity.TransportDetail;
import com.itmuch.cloud.study.service.TransportService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 作用：
 * ① 测试服务实例的相关内容
 * ② 为后来的服务做提供
 *
 * @author eacdy
 */
@RestController
public class TransportController {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private TransportService transportService;

    String url = "http://qr.huggies.com.cn/q/";


    /**
     * 注：@GetMapping("/{id}")是spring 4.3的新注解等价于：
     * @RequestMapping(value = "/id", method = RequestMethod.GET)
     * 类似的注解还有@PostMapping等等
     * @param
     * @return user信息
     */
    /**
     * @param plant                                       发货方
     * @param delivery                                    Delivery单号
     * @param docDate                                     接单日期20161212
     * @param requestDate                                 //要求发货日期
     * @param poNumber//采购订单编号
     * @param telNo                                       //收货人电话
     * @param headerInstruction//订单头备注--品类:84,部门:总部,类型:系统
     * @param routeCode                                   //线路代码
     * @param routeName//线路名称
     * @param solderCode//售达方代码
     * @param solderName                                  //售达方name
     * @param shiperCode//送达方代码
     * @param shiperName//送达方name
     * @param shiperAddress                               //售达方address
     * @param lineNum                                     //行号
     * @param refCode                                     //参考单号
     * @param reflineNum                                  //参考行号
     * @param materialCode                                //物料号
     * @param materialDescription                         //物料描述
     * @return
     */
    @ApiOperation(value = "通过restful调用创建订单信息", notes = "根据url传递的参数，持久化相关信息，注意1，订单新建状态如多次调用参数一致会覆盖原有订单2，参数必须都有值，如没有请传递null")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "plant", value = "发货方", required = true, dataType = "String"),
            @ApiImplicitParam(name = "delivery", value = "Delivery单号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "docDate", value = "接单日期,格式20181212", required = true, dataType = "String"),
            @ApiImplicitParam(name = "requestDate", value = "要求发货日期,格式20181112", required = true, dataType = "String"),
            @ApiImplicitParam(name = "poNumber", value = "采购订单编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "telNo", value = "收货人电话", required = true, dataType = "String"),
            @ApiImplicitParam(name = "headerInstruction", value = "订单头备注", required = true, dataType = "String"),
            @ApiImplicitParam(name = "routeCode", value = "线路代码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "routeName", value = "线路名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "solderCode", value = "售达方代码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "solderName", value = "售达方名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "shiperCode", value = "送达方代码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "shiperName", value = "送达方名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "shiperAddress", value = "送达方地址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "lineNum", value = "行号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "refCode", value = "参考单号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "reflineNum", value = "参考行号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "materialCode", value = "物料号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "materialDescription", value = "物料描述", required = true, dataType = "String"),
            @ApiImplicitParam(name = "productCode", value = "物料号旧代码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "custMaterial", value = "客户物料编码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "storageLocation", value = "金佰利系统存储库位", required = true, dataType = "String"),
            @ApiImplicitParam(name = "deliveryQty", value = "订货数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "salesUnit", value = "订货单位", required = true, dataType = "String"),
            @ApiImplicitParam(name = "detailInstruction", value = "订单明细备注", required = true, dataType = "String"),

    })
    @PostMapping("/saveOrder/{plant}/{delivery}/{docDate}/{requestDate}/{poNumber}/{telNo}/{headerInstruction}/{routeCode}/{routeName}/{solderCode}/{solderName}/{shiperCode}/{shiperName}/{shiperAddress}/{lineNum}/{refCode}/{reflineNum}/{materialCode}/{materialDescription}/{productCode}/{custMaterial}/{storageLocation}/{deliveryQty}/{salesUnit}/{detailInstruction}")
    public String saveOrder(@PathVariable String plant, @PathVariable String delivery, @PathVariable String docDate, @PathVariable String requestDate, @PathVariable String poNumber, @PathVariable String telNo, @PathVariable String headerInstruction, @PathVariable String routeCode, @PathVariable String routeName, @PathVariable String solderCode, @PathVariable String solderName, @PathVariable String shiperCode, @PathVariable String shiperName, @PathVariable String shiperAddress, @PathVariable String lineNum, @PathVariable String refCode, @PathVariable String reflineNum, @PathVariable String materialCode, @PathVariable String materialDescription, @PathVariable String productCode, @PathVariable String custMaterial, @PathVariable String storageLocation, @PathVariable String deliveryQty, @PathVariable String salesUnit, @PathVariable String detailInstruction) {
        System.out.println(plant + "-" + delivery + "-" + docDate + "-" + requestDate + "-" + poNumber + "-" + telNo + "-" + headerInstruction + "-" + routeCode + "-" + routeName + "-" + solderCode + "-" + solderName + "-" + shiperCode + "-" + shiperName + "-" + shiperAddress + "-" + lineNum + "-" + refCode + "-" + reflineNum + "-" + materialCode + "-" + materialDescription + "-" + productCode + "-" + custMaterial + "-" + storageLocation + "-" + deliveryQty + "-" + salesUnit + "-" + detailInstruction);
        return null;
    }

    @ApiOperation(value = "通过restful调用创建订单信息", notes = "根据url传递的参数，持久化相关信息")
    @PostMapping("/saveOrderwithEntity")
    @Transactional
    public String saveOrderwitEntity(@ApiParam @RequestBody Order order) {
        String message = "{\"msg\": \"保存失败,请检查信息后重试\",\"success\": false}";
        ;
        Transport transport = null;
        List<TransportDetail> transportDetails = null;
        if (order != null) {
            if (order.getTransport() != null) {
                transport = order.getTransport();
                if (order.getTransportDetails() != null && order.getTransportDetails().size() > 0) {
                    transportDetails = order.getTransportDetails();
                    message = transportService.saveOrderwitEntity(transport, transportDetails);
                }
            }

        }
        return message;
    }

    @GetMapping("/jdbcFind")
    public List<Transport> findAll() {
        return transportService.findAll();
    }


    /**
     * @Author： 齐丹枫
     * @Date: 2017/3/21
     * @Time: 8:56
     * @Method: findInfo
     * @Param: [search]
     * @Return: java.lang.String
     * 根据delivery区间，订单创建日期区间或者物料扫描日期区间，plantcode(user)查询所有物料信息
     */

    @PostMapping("/Find")
    public String findInfo(@RequestBody String search) {

        Message message = new Message();
        message.setMsg("条件不能为空");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        if (search == null || search.equals("")) {
            jo.put("message1", message);
            return jo.toString();
        }

        JSONObject obj = jo.parseObject(search);
        //日期格式：2016-01-23
        String createDate = obj.getString("sendDate");
        String plantCode = obj.getString("user");
        String scanDate = obj.getString("scanDate");
        String createDateStart = null;
        String createDateEnd = null;
        String scanDateStart = null;
        String scanDateEnd = null;
        if (createDate != null && !createDate.equals("")) {
            String[] str1 = createDate.split(",");
            if (str1.length == 2) {
                createDateStart = str1[0];
                createDateEnd = str1[1];
            }

        }

        if(scanDate != null && !scanDate.equals("")){
            String[] str1 = scanDate.split(",");
            if (str1.length == 2) {
                scanDateStart = str1[0];
                scanDateEnd = str1[1];
            }
        }

        String delivery = obj.getString("delivery");
        String deliveryStart = "";
        String deliveryEnd = "";
        if (delivery != null && !delivery.equals("")) {
            String[] str2 = delivery.split(",");
            if (str2.length == 1) {
                deliveryStart = str2[0];
            } else {
                deliveryStart = str2[0];
                deliveryEnd = str2[1];
            }
        }

        return transportService.find(createDateStart, createDateEnd, deliveryStart, deliveryEnd, plantCode,scanDateStart,scanDateEnd);
    }


    /**
     * @Author： 齐丹枫
     * @Date: 2017/3/21
     * @Time: 8:58
     * @Method: findDateByDevliery
     * @Param: [delivery]
     * @Return: java.lang.String
     * 根据delivery号查询下面的所有物料，包含扫描，未扫描。
     */
    @PostMapping("/FindDateInfo")
    public String findDateByDevliery(@RequestBody String delivery) {


        Message message = new Message();
        JSONObject jo = new JSONObject();
        JSONObject obj = jo.parseObject(delivery);
        if (delivery != null) {
            if (obj.get("delivery") != null && !obj.get("delivery").equals("")) {
                return transportService.findDateInfoByDelivery(obj.get("delivery").toString());
            }
        }
        message.setMsg("数据不能为空");
        message.setSuccess("false");
        jo.put("message", message);
        return jo.toString();

    }

    /**
     * @Author： 齐丹枫
     * @Date: 2017/3/21
     * @Time: 9:01
     * @Method: saveDeliverySkubarcode
     * @Param: [deliveryBarcode]
     * @Return: java.lang.String
     * 扫描接口
     */
    @PostMapping("/ScanDeliverySkubarcode")
    public String saveDeliverySkubarcode(@RequestBody String deliveryBarcode) {

        String message = "{\"msg\": \"数据不能为空\",\"success\": false}";
        if (deliveryBarcode == null || deliveryBarcode.equals("")) {
            return message;
        }
        JSONObject jsonObject = JSONObject.parseObject(deliveryBarcode);
        String delivery = jsonObject.getString("delivery");
        String barcode = "";
        if (jsonObject.getString("barcode").length() >= url.length()) {
            barcode = jsonObject.getString("barcode").substring(url.lastIndexOf("/") + 1);
        } else {
            barcode = jsonObject.getString("barcode");
        }
        //  String barcode = jsonObject.getString("barcode").substring(url.lastIndexOf("/")+1);
        if (delivery == null || delivery.equals("") || barcode == null || barcode.equals("")) {
            return message;
        }


        return transportService.saveDeliverySkubarcode(delivery, barcode);
    }


    /**
     * @Author： 齐丹枫
     * @Date: 2017/3/21
     * @Time: 9:02
     * @Method: deleteDeliverySkubarcode
     * @Param: [deliveryMaterial]
     * @Return: java.lang.String
     * 删除重扫接口，（1）输入delivery号，就删除下面的所有物料的所有以扫二维码，
     * （2）输入delivery，material号，就删除该delivery号下面对应的物料的以扫二维码
     * （3）输入delivery，material号，barcode(多个值以逗号分割)，删除对应的二维码
     */
    @PostMapping("/DeleteDeliverySkubarcode")
    public String deleteDeliverySkubarcode(@RequestBody String deliveryMaterial) {

        // String message = "{\"msg\": \"删除失败\",\"success\": false}";
        Message message = new Message();
        message.setMsg("删除失败");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        if (deliveryMaterial != null && !deliveryMaterial.equals("")) {
            JSONObject jsonObject = JSONObject.parseObject(deliveryMaterial);
            String delivery = jsonObject.getString("delivery");
            String material = jsonObject.getString("material");
            String[] str = jsonObject.getString("barcodes").split(",");
            String barcodes = "";

            for (int i = 0; i < str.length; i++) {
                String b = "";
                if (str[i].length() >= url.length()) {
                    b = str[i].substring(url.lastIndexOf("/") + 1);
                } else {
                    b = str[i];
                }
                barcodes = barcodes + b + ",";
            }


            if (delivery != null && !delivery.equals("")) {
                return transportService.deleteDeliverySkuBarcode(delivery, material, barcodes.substring(0, barcodes.length() - 1));
            }
        }
        return jo.put("message", message).toString();

    }


    /**
     * @Author： 齐丹枫
     * @Date: 2017/3/21
     * @Time: 9:03
     * @Method: getPrintSkuLabelInfo
     * @Param: [info]
     * @Return: java.lang.String
     * 打印箱单，根据delivery区间，物料号，barcode，plantcode(user)打印
     */
    @PostMapping("/PrintSkuLabelInfo")
    public String getPrintSkuLabelInfo(@RequestBody String info) {

        Message message = new Message();
        message.setMsg("数据不能为空");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        jo.put("message1", message);
        if (info == null || info.equals("")) {
            return jo.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(info);
        String deliverys = jsonObject.getString("delivery");
        String barcode = "";
        if (jsonObject.getString("barcode").length() >= url.length()) {
            barcode = jsonObject.getString("barcode").substring(url.lastIndexOf("/") + 1);
        } else {
            barcode = jsonObject.getString("barcode");
        }
        String materials = jsonObject.getString("material");
        String user = jsonObject.getString("user");
        if (deliverys == null || deliverys.equals("")) {
            return jo.toString();
        }
        String msg = null;
        try {
            String[] deliveryArry = deliverys.split(",");
            /**
             * 如果传入两个delivery号，说明是打印此区间的；如果是传入一个，就打印一个
             */
            if (deliveryArry.length != 0) {
                if (deliveryArry.length == 1) {
                    msg = transportService.findPrintSkuLabelInfo(deliveryArry[0], "", barcode, materials, user);
                } else {
                    msg = transportService.findPrintSkuLabelInfo(deliveryArry[0], deliveryArry[1], barcode, materials, user);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            message.setMsg("打印失败");
            message.setSuccess("false");
            jo.put("message1", message);
            return jo.toString();
        }
        return msg;

    }



    /**
     * @Author：    齐丹枫
     * @Date:       2017/3/21
     * @Time:       9:08
     * @Method:     printLabels
     * @Param:      [info]
     * @Return:     java.lang.String
     * 打印箱单，传入的delivery是以逗号分割的多个数据，物料号，barcode，plantcode(user)打印
     */
    @PostMapping("/PrintLabels")
    public String printLabels(@RequestBody String info) {
        Message message = new Message();
        message.setMsg("数据不能为空");
        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        jo.put("message1", message);
        if (info == null || info.equals("")) {
            return jo.toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(info);
        String deliverys = jsonObject.getString("delivery");
        String barcode = "";
        if (jsonObject.getString("barcode").length() >= url.length()) {
            barcode = jsonObject.getString("barcode").substring(url.lastIndexOf("/") + 1);
        } else {
            barcode = jsonObject.getString("barcode");
        }
        String materials = jsonObject.getString("material");
        String user = jsonObject.getString("user");
        if (deliverys == null || deliverys.equals("")) {
            message.setMsg("订单号不能为空");
            jo.put("message1",message);
            return jo.toString();
        }
        String msg = null;
        String str = "";
        try {
            String[] deliveryArry = deliverys.split(",");
            for (int i = 0; i < deliveryArry.length; i++) {
                str = str + "'" + deliveryArry[i] + "',";
            }

            msg = transportService.printLabels(str.substring(0, str.length() - 1), barcode, materials, user);
        } catch (Exception e) {
            //e.printStackTrace();
            message.setMsg("打印失败");
           //message.setSuccess("false");
            jo.put("message1", message);
            return jo.toString();
        }
        return msg;

    }


    /**
     * @Author：    齐丹枫
     * @Date:       2017/3/21
     * @Time:       9:09
     * @Method:     getPrintOrder
     * @Param:      [delivery]
     * @Return:     java.lang.String
     * 结单接口，根据delivery号，物料没有扫完不能结单。
     */
    @PostMapping("/PrintOrder")
    public String getPrintOrder(@RequestBody String delivery) {

        String message = "{\"msg\": \"数据不能为空\",\"success\": false}";
        if (delivery == null || delivery.equals("")) {
            return message;
        }
        JSONObject jsonObject = JSONObject.parseObject(delivery);
        String deliveryNum = jsonObject.get("delivery").toString();

        message = transportService.getPrintOrder(deliveryNum,true);

        return message;

    }

    /**
     * @Author：    齐丹枫
     * @Date:       2017/4/18
     * @Time:       10:21
     * @Method:     forceTogetPrintOrder
     * @Param:      [request]
     * @Return:     java.lang.String
     * 强制结单
     */
    @PostMapping("/forceTogetPrintOrder")
    public  String forceTogetPrintOrder(@ RequestBody String request){

        Message message = new Message();

        message.setSuccess("false");
        JSONObject jo = new JSONObject();
        if(request == null || request.equals("")){
            message.setMsg("数据不能为空");
            return  jo.put("message1",message).toString();
        }
        JSONObject jsonObject = JSONObject.parseObject(request);

        String delivery = jsonObject.getString("delivery");
        if(delivery == null || "".equals(delivery)){
            message.setMsg("单号不能为空");
            return  jo.put("message1",message).toString();
        }

        String msg = "";
        msg = transportService.getPrintOrder(delivery,false);
        return msg;
    }



    /**
     * 本地服务实例的信息
     *
     * @return
     */
    @GetMapping("/instance-info")
    public ServiceInstance showInfo() {
        ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();
        return localServiceInstance;
    }
}
